package com.windoent.yugioh.ui.fragment.saishi.ongoing;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.OnGoingHasEndSaiGuoLunsAdapter;
import com.windoent.yugioh.adapter.brvah.SaiGuoTitleAdapter;
import com.windoent.yugioh.base.BaseFragment;
import com.windoent.yugioh.bean.GameStatusRoleBean;
import com.windoent.yugioh.bean.OnGoingHasEndLunBean;
import com.windoent.yugioh.bean.eventbus.FragmentActivityMessageEvent;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.saishi.StoreGradeCommitDocumentActvity;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.SimpleUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.RoundImageView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/24 10:40
 * desc   :saiguo赛果
 */
public class OnGoingSaiGuoFragment extends BaseFragment {
    private Button mBtnGetCode;
    private SmartRefreshLayout mSmartLayout;
    private RecyclerView mRecyclerView;
    private LinearLayout mLlNodata;
    private LinearLayout mLlBottom;
    private TextView mTvNumbers;
    private RoundImageView mIvAvatar;
    private TextView mTvName;
    private TextView mTvRank;
    private TextView mTvPoints;
    private RecyclerView mRecyclerViewTitle;
    private NestedScrollView mScrollView;

    private String limit = Constants.PAGETEN;
    private int mCount = 1;
    private OnGoingHasEndSaiGuoLunsAdapter adapter;
    private SaiGuoTitleAdapter adapterTitle;
    private int applayStatus = -1;
    private boolean ignore;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_saishi_ongoing_saiguo;
    }

    public static OnGoingSaiGuoFragment newsInstance(String id) {
        //创建 Bundle
        OnGoingSaiGuoFragment fragment = new OnGoingSaiGuoFragment();
        Bundle lBundle = new Bundle();
        lBundle.putString("id", id);
        fragment.setArguments(lBundle);
        return fragment;
    }

    @Override
    protected void initEventAndData() {
        initView();
        initData();
        initListener();
    }

    private void initData() {
        initAdapter();
        initTitleAdapter();
        showNodata(true);
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new OnGoingHasEndSaiGuoLunsAdapter();
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {

            }
        });
    }

    private void initTitleAdapter() {
        mRecyclerViewTitle.setLayoutManager(new LinearLayoutManager(mContext));
        adapterTitle = new SaiGuoTitleAdapter();
        mRecyclerViewTitle.setNestedScrollingEnabled(false);
        mRecyclerViewTitle.setAdapter(adapterTitle);
        adapterTitle.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {

            }
        });
    }

    private void initListener() {
        mBtnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //
                Intent intent = new Intent(mContext, StoreGradeCommitDocumentActvity.class);
                intent.putExtra("id", id);
                intent.putExtra("applayStatus", applayStatus);
                intent.putExtra("ignore", ignore);
                startActivity(intent);
            }
        });
    }

    private void initView() {

        mBtnGetCode = (Button) mView.findViewById(R.id.btn_get_code);
        mSmartLayout = (SmartRefreshLayout) mView.findViewById(R.id.smart_layout);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);
        mLlNodata = (LinearLayout) mView.findViewById(R.id.ll_nodata);
        mLlBottom = (LinearLayout) mView.findViewById(R.id.ll_bottom);
        mTvNumbers = (TextView) mView.findViewById(R.id.tv_numbers);
        mIvAvatar = (RoundImageView) mView.findViewById(R.id.iv_avatar);
        mTvName = (TextView) mView.findViewById(R.id.tv_name);
        mTvRank = (TextView) mView.findViewById(R.id.tv_rank);
        mTvPoints = (TextView) mView.findViewById(R.id.tv_points);

        mRecyclerViewTitle = (RecyclerView) mView.findViewById(R.id.recycler_view_title);
        mScrollView = (NestedScrollView) mView.findViewById(R.id.scroll_view);
    }

    //无数据ui显示
    private void showNodata(boolean noData) {
        mBtnGetCode.setVisibility(noData ? View.GONE : View.VISIBLE);
        mLlBottom.setVisibility(noData ? View.GONE : View.VISIBLE);
        mScrollView.setVisibility(noData ? View.GONE : View.VISIBLE);
        mLlNodata.setVisibility(noData ? View.VISIBLE : View.GONE);
    }

    private void initRefreshData() {
        //下拉刷新
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh();
            }
        });
        //加载更多
        mSmartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                loadMore();
            }
        });
    }

    private void loadMore() {
        mCount = mCount + 1;
        reviewAgainstResult(mCount + "", limit, false);
    }

    private void fresh() {
        getGameStatusRole(id);
    }

    //获取赛事状态角色
    private void getGameStatusRole(String id) {
        showLoadingDialog("");
        PhoneLive.getGameStatusRole(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GameStatusRoleBean json = gson.fromJson(response, GameStatusRoleBean.class);
                            if (json != null) {
                                GameStatusRoleBean.DataBean data = json.getData();
                                if (data != null) {
                                    String role = data.getRole();
                                    int statusid = data.getStatusid();
                                    if (statusid == 8) {
                                        //发送eventbus粘性事件
                                        FragmentActivityMessageEvent event = new FragmentActivityMessageEvent();
                                        event.setMessage(1);
                                        event.setRole(role);
                                        event.setStatusId(statusid);
                                        EventBus.getDefault().postSticky(event);
                                    } else if (statusid != 2 && statusid != 8) {
                                        mCount = 1;
                                        reviewAgainstResult(mCount + "", limit, true);
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //查看赛果
    private void reviewAgainstResult(String page, String limit, boolean fresh) {
        showLoadingDialog("");
        PhoneLive.reviewAgainstResult(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                freshFail(fresh);
                showNodata(true);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            OnGoingHasEndLunBean json = gson.fromJson(response, OnGoingHasEndLunBean.class);
                            if (json != null) {
                                OnGoingHasEndLunBean.DataBean data = json.getData();
                                if (data != null) {
                                    boolean hasData = (data.isIsOff() && data.getAgainstResultOff() != null && data.getAgainstResultOff().size() > 0) || (data.getAgainstResultSwiss() != null && data.getAgainstResultSwiss().size() > 0) || (data.getCurrentUser() != null && data.getCurrentUser().getRank() != 0);
                                    showNodata(!hasData);
                                    //申请结束比赛状态 ：0没有操作权限 1,还没申请 (结束比赛) 2，已经申请，正在审核（审核中） 3，审核通过 （已结束比赛） 4，审核不通过（重新提交）
                                    applayStatus = data.getApplayStatus();
                                    showBtnStatus(applayStatus);
                                    ignore = data.isIgnore();//忽略跳过字段

                                    OnGoingHasEndLunBean.DataBean.CurrentUserBean currentUser = data.getCurrentUser();
                                    mLlBottom.setVisibility(currentUser == null || currentUser.getRank() == 0 ? View.GONE : View.VISIBLE);
                                    if (currentUser != null) {
                                        setUserInfo(currentUser);
                                    }
                                    List<OnGoingHasEndLunBean.DataBean.AgainstResultOffBean> againstResultOff = data.getAgainstResultOff();
                                    String againstSwissTitle = data.getAgainstSwissTitle();
                                    if (againstResultOff != null) {
                                        boolean isOff = data.isIsOff();//是否显示决赛模块（true : 是 false:否）
                                        if (adapterTitle.getHeaderLayoutCount() > 0) {
                                            adapterTitle.removeAllHeaderView();
                                        }
                                        mRecyclerViewTitle.setVisibility(isOff ? View.VISIBLE : View.GONE);
                                        if (isOff) {
                                            assert adapterTitle != null;
                                            addTiTleHeader();
                                            adapterTitle.setNewInstance(againstResultOff);
                                        }
                                    } else {
                                        mRecyclerViewTitle.setVisibility(View.GONE);
                                    }
                                    List<OnGoingHasEndLunBean.DataBean.CurrentUserBean> againstResultSwiss = data.getAgainstResultSwiss();
                                    if (againstResultSwiss != null) {
                                        if (adapter.getHeaderLayoutCount() > 0) {
                                            adapter.removeAllHeaderView();
                                        }
                                        addSwissTiTleHeader(againstSwissTitle);
                                        addRvTiTleHeader();
                                    }
                                    if (againstResultSwiss != null) {
                                        if (fresh) {
                                            adapter.setNewInstance(againstResultSwiss);
                                            mSmartLayout.finishRefresh(true);
                                        } else {
                                            adapter.addData(againstResultSwiss);
                                            adapter.notifyDataSetChanged();
                                            mSmartLayout.finishLoadMore(true);
                                        }
                                    } else freshFail(fresh);
                                } else {
                                    freshFail(fresh);
                                    showNodata(true);
                                }
                            } else {
                                freshFail(fresh);
                                showNodata(true);
                            }
                        } else {
                            showNodata(true);
                            freshFail(fresh);
                        }
                    } catch (JSONException e) {
                        showNodata(true);
                        freshFail(fresh);
                        e.printStackTrace();
                    }
                } else {
                    showNodata(true);
                    freshFail(fresh);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }


    //淘汰赛标题
    private void addTiTleHeader() {
        if (isAdded() && getActivity() != null) {
            View headView = getLayoutInflater().inflate(R.layout.head_rv_view_saiguo_title, (ViewGroup) mRecyclerView.getParent(), false);
            if (adapterTitle != null) {
                adapterTitle.addHeaderView(headView);
                adapterTitle.setHeaderWithEmptyEnable(true);
            }
        }
    }

    //rv标题（xx轮）
    private void addSwissTiTleHeader(String title) {
        if (isAdded() && getActivity() != null) {
            View headView = getLayoutInflater().inflate(R.layout.head_rv_view_saiguo_swiss_title, (ViewGroup) mRecyclerView.getParent(), false);
            TextView tv_title = headView.findViewById(R.id.tv_title);
            tv_title.setText(BaseMethod.notNullDefaultValueNull(title));
            if (adapter != null) {
                adapter.addHeaderView(headView);
                adapter.setHeaderWithEmptyEnable(true);
            }
        }
    }

    //rv横标题
    private void addRvTiTleHeader() {
        if (isAdded() && getActivity() != null) {
            View headView = getLayoutInflater().inflate(R.layout.head_rv_view_saiguo_rv_title, (ViewGroup) mRecyclerView.getParent(), false);
            if (adapter != null) {
                adapter.addHeaderView(headView);
                adapter.setHeaderWithEmptyEnable(true);
            }
        }
    }

    //申请结束比赛状态 ：0没有操作权限 1,还没申请 (结束比赛) 2，已经申请，正在审核（审核中） 3，审核通过 （已结束比赛） 4，审核不通过（重新提交）
    private void showBtnStatus(int applayStatus) {
        if (applayStatus == 0) {
            mBtnGetCode.setBackgroundResource(R.drawable.drawable_manager_game_btn_gary_bg);
            mBtnGetCode.setText(R.string.string_no_permission_saiguo_warning);
            mBtnGetCode.setVisibility(View.GONE);
        } else if (applayStatus == 1) {
            mBtnGetCode.setBackgroundResource(R.drawable.drawable_login_getcode_bg);
            mBtnGetCode.setText(R.string.string_over_game);
            mBtnGetCode.setVisibility(View.VISIBLE);
        } else if (applayStatus == 2) {
            mBtnGetCode.setBackgroundResource(R.drawable.drawable_manager_game_btn_gary_bg);
            mBtnGetCode.setText(R.string.string_reviewing);
            mBtnGetCode.setVisibility(View.VISIBLE);
        } else if (applayStatus == 3) {
            mBtnGetCode.setBackgroundResource(R.drawable.drawable_manager_game_btn_gary_bg);
            mBtnGetCode.setText(R.string.string_sure_saiguo_pass_warn);
            mBtnGetCode.setVisibility(View.VISIBLE);
        } else if (applayStatus == 4) {
            mBtnGetCode.setBackgroundResource(R.drawable.drawable_login_getcode_bg);
            mBtnGetCode.setText(R.string.string_resubmit_warn);
            mBtnGetCode.setVisibility(View.VISIBLE);
        }

    }

    //底部自己信息
    private void setUserInfo(OnGoingHasEndLunBean.DataBean.CurrentUserBean currentUser) {
        SimpleUtils.loadImageForView(mContext, mIvAvatar, currentUser.getAvatar(), R.drawable.img_official_avatar_android);
        setText(mTvNumbers, currentUser.getRank() + "");
        setText(mTvName, currentUser.getNickname());
        setText(mTvRank, currentUser.getScore() + "");
        setText(mTvPoints, currentUser.getTiebreaker() + "");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    //刷新失败
    private void freshFail(boolean fresh) {
        if (fresh) {
            adapter.setNewInstance(null);
            mSmartLayout.finishRefresh(false);
        } else {
            mSmartLayout.finishLoadMore(false);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageEnd(getActivity(), "赛事已结束赛果tab");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageStart(getActivity(), "赛事已结束赛果tab");
        }
        getDetailsId();
    }

    private String id = "";

    //获取activity传值id
    private void getDetailsId() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            id = bundle.getString("id");
            initRefreshData();
            fresh();
        }
    }
}
